package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.common.resp.RespBean;
import com.xxxx.server.common.resp.RespPageBean;
import com.xxxx.server.mapper.EmployeeMapper;
import com.xxxx.server.mapper.MailLogMapper;
import com.xxxx.server.pojo.Employee;
import com.xxxx.server.pojo.MailConstants;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IEmployeeService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2021-12-20
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    MailLogMapper mailLogMapper;

    // 分页获取所有员工(包括模糊查询)
    @Override
    public RespPageBean getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        // 开启分页
        Page<Employee> page = new Page<>(currentPage,size);
        // 把分页的数据封装后进行查询 查询出来后进一步封装（要多少条查多少条）
        IPage<Employee> employeeByPage = employeeMapper.getEmployeeByPage(page,employee,beginDateScope);
        // 拿出查出来，封装后的数据的总条数和内容
        RespPageBean respPageBean = new RespPageBean(employeeByPage.getTotal(),employeeByPage.getRecords());
        return respPageBean;
    }

    // 获取工号
    @Override
    public RespBean getMaxWorkID() {
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        Integer maxWorkID = Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1;
        return RespBean.success("获取最新工号成功！",String.format("%08d",maxWorkID));
    }

    // 添加员工
    @Override
    public RespBean addEmp(Employee employee) {
        // 处理合同期限，保留两位小数
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365)));

        if (1 == employeeMapper.insert(employee)) {
            // 查询员工 - 当传入ID时查询此员工的信息,当未传入ID时查询所有员工信息
            // 此处传入了id,所以返回值虽然是List但只有一个值,直接get(0)获取
            Employee emp = employeeMapper.getEmployee(employee.getId()).get(0);
            // 使用UUID生成消息ID
            String msgId = UUID.randomUUID().toString();
//            String msgId = "123456789";  // 消息的幂等性测试,设置固定的消息ID
            // 设置MailLog
            MailLog mailLog = new MailLog();
            // 写入消息ID
            mailLog.setMsgId(msgId);
            // 写入员工id
            mailLog.setEid(emp.getId());
            // 写入消息状态
            mailLog.setStatus(0);
            // 写入路由键
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            // 写入交换机
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            // 写入重试次数
            mailLog.setCount(0);
            // 写入重试时间  在当前时间往后推一分钟
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            // 创建时间
            mailLog.setCreateTime(LocalDateTime.now());
            // 更新时间
            mailLog.setUpdateTime(LocalDateTime.now());
            // 消息入库
            mailLogMapper.insert(mailLog);
            // rabbitMQ传递消息
            // 传递对象: emp 注意发送消息的传递对象必须实现Serializable接口
            // 这里传递的是从数据库中获取的员工完整信息,对象中包含字典对象的属性
            // 不能直接用添加员工功能传进来的信息, 应为不包含字段对象的属性,只有ID
            // 设置邮件内容的时候获取不到我们要的属性, 会异常
            // CorrelationData 带上这个在发送消息的时候才能获取到msgId
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,
                    MailConstants.MAIL_ROUTING_KEY_NAME,
                    emp,
                    new CorrelationData(msgId));
            return RespBean.success("添加员工信息成功!");
        }
        return RespBean.error("添加员工信息失败!");
    }

    // 获取导出员工信息
    @Override
    public List<Employee> getEmployee(Integer id) {
        return employeeMapper.getEmployee(id);
    }

    // 获取所有员工账套
    @Override
    public RespPageBean getEmployeeWithSalary(Integer currentPage, Integer size) {
        Page<Employee> page = new Page<>(currentPage,size);
        IPage<Employee> employeeIPage = employeeMapper.getEmployeeWithSalary(page);
        RespPageBean respPageBean = new RespPageBean(employeeIPage.getTotal(),employeeIPage.getRecords());
        return respPageBean;
    }
}
